export function convertHighLow(str) {
  const high = str.substr(-4)
  const low = str.substr(0, 4)

  return high + low
}

export function convertHex2Bin(hex, length) {
  const ten = parseInt(hex, 16)
  let bin = ten.toString(2)
  bin = bin.padStart(length, 0)
  return bin
}

export function FillString(t, c, n, b) {
  if ((t === '') || (c.length !== 1) || (n <= t.length)) {
    return t
  }
  var l = t.length
  for (var i = 0; i < n - l; i++) {
    if (b === true) {
      t = c + t
    } else {
      t += c
    }
  }
  return t
}

export function hexToSingle(t) {
  t = t.replace(/\s+/g, '')
  if (t === '') {
    return ''
  }
  if (t === '00000000') {
    return '0'
  }
  if ((t.length > 8) || (isNaN(parseInt(t, 16)))) {
    return 'Error'
  }
  if (t.length < 8) {
    t = FillString(t, '0', 8, true)
  }
  t = parseInt(t, 16).toString(2)
  t = FillString(t, '0', 32, true)
  var s = t.substring(0, 1)
  var e = t.substring(1, 9)
  var m = t.substring(9)
  e = parseInt(e, 2) - 127
  m = '1' + m
  if (e >= 0) {
    m = m.substr(0, e + 1) + '.' + m.substring(e + 1)
  } else {
    m = '0.' + FillString(m, '0', m.length - e - 1, true)
  }
  if (m.indexOf('.') === -1) {
    m = m + '.0'
  }
  var a = m.split('.')
  var mi = parseInt(a[0], 2)
  var mf = 0
  for (var i = 0; i < a[1].length; i++) {
    mf += parseFloat(a[1].charAt(i)) * Math.pow(2, -(i + 1))
  }
  m = parseInt(mi) + parseFloat(mf)
  if (s === 1) {
    m = 0 - m
  }
  return m
}

export function buf2hex(buffer) { // buffer is an ArrayBuffer
  return Array.prototype.map.call(new Uint8Array(buffer), x => ('00' + x.toString(16).toUpperCase()).slice(-2)).join('')
}

export function convert(value) { // 转ArrayBuffer数据
  var typedArray = new Uint8Array(value.match(/[\da-f]{2}/gi).map(function(h) {
    return parseInt(h, 16)
  }))
  return typedArray.buffer
}

export function crc32(str) {
  var isArray = function(arr) {
    return Object.prototype.toString.call(arr) === '[object Array]'
  }

  var convertChinese = function(str) {
    var tmp = str.split('')
    var arr = []
    for (var i = 0, c = tmp.length; i < c; i++) {
      var s = tmp[i].charCodeAt()
      if (s <= 0 || s >= 127) {
        arr.push(s.toString(16))
      } else {
        arr.push(tmp[i])
      }
    }
    return arr
  }

  var filterChinese = function(str) {
    var tmp = str.split('')
    var arr = []
    for (var i = 0, c = tmp.length; i < c; i++) {
      var s = tmp[i].charCodeAt()
      if (s > 0 && s < 127) {
        arr.push(tmp[i])
      }
    }
    return arr
  }

  var strToHex = function(hex, isFilterChinese) {
    hex = isFilterChinese ? filterChinese(hex).join('') : convertChinese(hex).join('')

    // 清除所有空格
    hex = hex.replace(/\s/g, '')
    // 若字符个数为奇数，补一个空格
    hex += hex.length % 2 !== 0 ? ' ' : ''

    var c = hex.length / 2
    var arr = []
    for (var i = 0; i < c; i++) {
      arr.push(parseInt(hex.substr(i * 2, 2), 16))
    }
    return arr
  }

  var padLeft = function(s, w, pc) {
    if (pc === undefined) {
      pc = '0'
    }
    for (var i = 0, c = w - s.length; i < c; i++) {
      s = pc + s
    }
    return s
  }

  var crc16 = function(data) {
    var len = data.length
    if (len > 0) {
      var crc = 0xFFFF

      for (var i = 0; i < len; i++) {
        crc = (crc ^ (data[i]))
        for (var j = 0; j < 8; j++) {
          crc = (crc & 1) !== 0 ? ((crc >> 1) ^ 0xA001) : (crc >> 1)
        }
      }
      var hi = ((crc & 0xFF00) >> 8) // 高位置
      var lo = (crc & 0x00FF) // 低位置

      return [lo, hi]
    }
    return [0, 0]
  }

  strToHex = function(hex, isFilterChinese) {
    hex = isFilterChinese ? filterChinese(hex).join('') : convertChinese(hex).join('')

    // 清除所有空格
    hex = hex.replace(/\s/g, '')
    // 若字符个数为奇数，补一个空格
    hex += hex.length % 2 !== 0 ? ' ' : ''

    var c = hex.length / 2
    var arr = []
    for (var i = 0; i < c; i++) {
      arr.push(parseInt(hex.substr(i * 2, 2), 16))
    }
    return arr
  }

  var tostring = function(arr, isReverse) {
    if (isReverse) {
      isReverse = true
    }
    var hi = arr[0]
    var lo = arr[1]
    return padLeft((isReverse ? hi + lo * 0x100 : hi * 0x100 + lo).toString(16).toUpperCase(), 4, '0')
  }

  return tostring(crc16(isArray(str) ? str : strToHex(str)))
}

// 解析所需数据
export function formatInitial(value) {
  if (value.length === 82) {
    const dataStr = value.substr(6, 72)
    const CH = dataStr.substr(44, 4)
    const RTUID = parseInt(`0x${dataStr.substr(36, 4)}`)
    const LCP = parseInt(`0x${dataStr.substr(68, 4)}`)
    const MSG = parseInt(`0x${dataStr.substr(0, 4)}`)

    const AESKEY = dataStr.substr(48, 4)
    const TRSF = dataStr.substr(52, 4)
    const TPREM = dataStr.substr(56, 4)
    const RPREM = dataStr.substr(60, 4)
    const TRIQ = dataStr.substr(64, 4)
    return {
      CH, RTUID, LCP, MSG, AESKEY, TRSF, TPREM, RPREM, TRIQ
    }
  }
  return {
    CH: '',
    RTUID: '',
    LCP: '',
    MSG: '',
    AESKEY: '',
    TRSF: '',
    TPREM: '',
    RPREM: '',
    TRIQ: ''
  }
}
